package com.example.ktpspringboot.service.impl;

import com.example.ktpspringboot.entity.Course;
import com.example.ktpspringboot.entity.Student;
import com.example.ktpspringboot.entity.Teacher;
import com.example.ktpspringboot.mapper.CourseMapper;
import com.example.ktpspringboot.mapper.StudentMapper;
import com.example.ktpspringboot.service.CourseService;
import com.example.ktpspringboot.utils.SnowflakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.Random;
import java.util.regex.Pattern;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SnowflakeUtil snowflakeUtil;

    String judgePhone = "^\\d{11}$";
    String judgeEmail = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$";
    String judgeAccount = "^ktp\\d{10}$";
    private static final String COURSE_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int COURSE_CODE_LENGTH = 6;


    @Override
    public List<Course> getStudyCourse(String username, String role) {
        if (role.equals("student")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.queryStuStudyCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.queryStuStudyCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.queryStuStudyCourseByAccount(username);
            }
        } else if (role.equals("teacher")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.queryTeaStudyCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.queryTeaStudyCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.queryTeaStudyCourseByAccount(username);
            }
        }
        return null;
    }

    @Override
    public List<Course> getTeachCourse(String username, String role) {
        if (role.equals("teacher")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.queryTeachCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.queryTeachCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.queryTeachCourseByAccount(username);
            }
        } else {
            return null;
        }
        return null;
    }

    @Override
    public List<Course> getHelpCourse(String username, String role) {
        if (role.equals("student")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.queryStuHelpCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.queryStuHelpCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.queryStuHelpCourseByAccount(username);
            }
        } else if (role.equals("teacher")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.queryTeaHelpCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.queryTeaHelpCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.queryTeaHelpCourseByAccount(username);
            }
        }
        return null;
    }

    @Override
    public List<Course> getTopCourse(String username, String role) {
        if (role.equals("student")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.findStuTopCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.findStuTopCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.findStuTopCourseByAccount(username);
            }
        } else if (role.equals("teacher")) {
            if (dataVerification(username, judgePhone)) {
                return courseMapper.findTeaTopCourseByPhone(username);
            } else if (dataVerification(username, judgeEmail)) {
                return courseMapper.findTeaTopCourseByEmail(username);
            } else if (dataVerification(username, judgeAccount)) {
                return courseMapper.findTeaTopCourseByAccount(username);
            }
        }
        return null;
    }

    @Override
    public String joinCourse(String code, String username, String role) {
        if (role.equals("student")) {
            if (dataVerification(username, judgePhone)) {
                String stuUuid = courseMapper.findStuByPhone(username);
                return getStuString(code, stuUuid);
            } else if (dataVerification(username, judgeEmail)) {
                String stuUuid = courseMapper.findStuByEmail(username);
                return getStuString(code, stuUuid);
            } else if (dataVerification(username, judgeAccount)) {
                String stuUuid = courseMapper.findStuByAccount(username);
                return getStuString(code, stuUuid);
            }
        } else if (role.equals("teacher")) {
            if (dataVerification(username, judgePhone)) {
                String teaUuid = courseMapper.findTeaByPhone(username);
                return getTeaString(code, teaUuid);
            } else if (dataVerification(username, judgeEmail)) {
                String teaUuid = courseMapper.findTeaByEmail(username);
                return getTeaString(code, teaUuid);
            } else if (dataVerification(username, judgeAccount)) {
                String teaUuid = courseMapper.findTeaByAccount(username);
                return getTeaString(code, teaUuid);
            }
        }
        return "";
    }

    @Override
    public void dealWithTeachingMode(String teachingMode, Course course) {
        switch (teachingMode) {
            case "线上":
                course.setIsOffline(1);
                course.setIsTop(0);
                course.setIsMix(0);
                break;
            case "线下":
            case "":
                course.setIsOffline(0);
                course.setIsTop(0);
                course.setIsMix(0);
                break;
            case "混合":
                course.setIsOffline(0);
                course.setIsTop(0);
                course.setIsMix(1);
                break;
            default:
                System.out.println("传输数据出现问题");
        }
    }

    @Override
    public String establishCourseQueryTeaName(String userName) {
        if (dataVerification(userName, judgePhone)) {
            return studentMapper.queryByPhone(userName).getName();
        } else if (dataVerification(userName, judgeEmail)) {
            return studentMapper.queryByEmail(userName).getName();
        } else if (dataVerification(userName, judgeAccount)) {
            return studentMapper.queryByAccount(userName).getName();
        }
        return null;
    }

    @Override
    public String establishCourseQueryTeaUuid(String userName) {
        if (dataVerification(userName, judgePhone)) {
            return studentMapper.queryByPhone(userName).getUuid();
        } else if (dataVerification(userName, judgeEmail)) {
            return studentMapper.queryByEmail(userName).getUuid();
        } else if (dataVerification(userName, judgeAccount)) {
            return studentMapper.queryByAccount(userName).getUuid();
        }
        return null;
    }

    private String getTeaString(String code, String teaUuid) {
        String courseUuid = courseMapper.findCourseByCode(code);
        if (courseUuid == null) {
            return "不存在该课程";
        } else {
            String stId = courseMapper.selectTeaCourse(teaUuid, courseUuid);
            if (stId == null) {
                int total = courseMapper.insertTeacherStudyCourse(teaUuid, courseUuid);
                if (total > 0) {
                    courseMapper.updateCourseNumber(courseUuid);
                    return "加入课程成功";
                } else {
                    return "加入课程失败，数据库并没有新增数据成功";
                }
            } else {
                return "加入课程失败，原因是该老师已经加入该课程";
            }
        }
    }

    private String getStuString(String code, String stuUuid) {
        String courseUuid = courseMapper.findCourseByCode(code);
        if (courseUuid == null) {
            return "不存在该课程";
        } else {
            String stId = courseMapper.selectStuCourse(stuUuid, courseUuid);
            if (stId == null) {
                int total = courseMapper.insertStudentStudyCourse(stuUuid, courseUuid);
                if (total > 0) {
                    courseMapper.updateCourseNumber(courseUuid);
                    return "加入课程成功";
                } else {
                    return "加入课程失败，数据库并没有新增数据成功";
                }
            } else {
                return "加入课程失败，原因是该学生已经加入该课程";
            }
        }
    }

    @Override
    public boolean dataVerification(String arg, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(arg);
        boolean matchesId = matcher.matches();
        if (arg.equals("")) {
            return false;
        }
        return matchesId;
    }

    @Override
    public String generateEnrollmentCode() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < COURSE_CODE_LENGTH; i++) {
            int index = random.nextInt(COURSE_CODE.length());
            sb.append(COURSE_CODE.charAt(index));
        }
        return sb.toString();
    }

    @Override
    public int gainStudentNumber(String studyClass) {
        return courseMapper.selectStudentNumber(studyClass);
    }

    @Override
    public String establishCourse(Course course, String username) {
        int total = courseMapper.insertCourse(course);
        if (total == 0) {
            return "新增课程信息失败，数据库没有成功存储课程信息";
        } else {
            String teaUuid = establishCourseQueryTeaUuid(username);
            int total1 = courseMapper.insertTeacherTeachCourse(teaUuid, course.getUuid());
            if (total1 > 0) {
                return "新增课程成功";
            } else {
                return "新增老师与课程的关系失败，数据库并没有将老师与课程的关系存储下来";
            }
        }
    }

    @Override
    public String topping(String courseCode) {
        int i = courseMapper.toppingCourse(courseCode);
        if (i == 0) {
            return "置顶课程失败，数据库数据没有变化";
        } else {
            return "置顶课程成功";
        }
    }

    @Override
    public String cancelTopping(String courseCode) {
        int i = courseMapper.cancelToppingCourse(courseCode);
        if (i == 0) {
            return "取消置顶课程失败，数据库数据没有变化";
        } else {
            return "取消置顶课程成功";
        }
    }

    @Override
    public String preserveUrl() {
        String url = "https://assets.ketangpai.com/theme/min/0" + (int) ((Math.random() * 10) + 1) + ".jpg";
        System.out.println(url);
        return url;
    }

    /**
     * 通过课程code获取课程id
     * @param courseCode
     * @return
     */
    @Override
    public List<Teacher> getCourseIdByCode(String courseCode) {
        return courseMapper.findTeacherByCourseCode(courseCode);
    }


    /**
     * 通过课程号查询到课程id，再通过课程id查询到学生id，再通过学生id查询到学生学号、姓名和学校
     * @param courseCode
     * @return
     */
    @Override
    public List<Student> getCourseIdByCodeForStudent(String courseCode) {
        return studentMapper.queryByCourseCode(courseCode);
    }

    /**
     * 通过课程号查询到课程id，最终计算出满足条件的教师人数
     * @param courseCode
     * @return
     */
    @Override
    public int sumTeacher(String courseCode) {
        return courseMapper.countTeacherByCourseCode(courseCode);
    }

    /**
     * 通过课程号查询到课程id，最终计算出满足条件的学生人数
     * @param courseCode
     * @return
     */
    @Override
    public int sumStudent(String courseCode) {
        return studentMapper.countStudentsByCourseCode(courseCode);
    }


}
